﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Yhb.Config;
using Yhb.Utility;

namespace TradeSyncNotify.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }


        [HttpPost]
        public string DealNotifyData()
        {

            var serverSign = HttpContext.Request.Headers["sign"];
            Console.WriteLine("异步通知serverSign:" + serverSign);
            var stream = HttpContext.Request.InputStream;
            stream.Position = 0;
            var requestData="";
            using (var streamReader = new StreamReader(stream, Encoding.UTF8))
            {
                requestData = streamReader.ReadToEndAsync().Result;
                Console.WriteLine("异步通知body:" + requestData);
                stream.Position = 0;
            }
            bool verifyResult = RSAUtility.Verify(requestData, serverSign, SignConfig.EHB_PUBLIC_KEY);
            if (verifyResult)
            {
                Dictionary<string, object> resultObj = JsonToDictionary(requestData);
                object mType = getValueDictionaryByKey(resultObj, "type");
                object timeCreated = getValueDictionaryByKey(resultObj, "timeCreated");
                object notifyNo = getValueDictionaryByKey(resultObj, "notifyNo");

                Dictionary<string, object> data = (Dictionary<string, object>)getValueDictionaryByKey(resultObj, "data");
                // 公共响应参数
                object order_no = getValueDictionaryByKey(data, "order_no");
                object merchant_order_no = getValueDictionaryByKey(data, "merchant_order_no");
                object return_code = getValueDictionaryByKey(data, "return_code");
                object return_msg = getValueDictionaryByKey(data, "return_msg");
                object err_code = getValueDictionaryByKey(data, "err_code");
                object err_code_desc = getValueDictionaryByKey(data, "err_code_desc");
                object status = getValueDictionaryByKey(data, "status");

                if ("CHARGE".Equals(mType)) // 支付
                {
                    object trade_type = getValueDictionaryByKey(data, "trade_type");
                }
                else if ("REFUND".Equals(mType)) // 退款
                {
                    object refund_order_no = getValueDictionaryByKey(data, "refund_order_no");
                    object merchant_refund_order_no = getValueDictionaryByKey(data, "merchant_refund_order_no");
                }
            } else
            {
                Console.WriteLine("异步通知验签失败");
                return "fail";
            }
            return "success";
        }

        /// <summary>
        /// 将json数据反序列化为Dictionary
        /// </summary>
        /// <param name="jsonData">json数据</param>
        /// <returns></returns>
        private Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            //实例化JavaScriptSerializer类的新实例
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
                return jss.Deserialize<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 根据键值从字典表中获取键值对应的数值,键值不存在，默认返回null
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private object getValueDictionaryByKey(Dictionary<string, object> data, string key)
        {
            if (data.ContainsKey(key))
            {
                return data[key];
            }
            return null;
        }
    }
}
